import React, { Component } from 'react';
import { Icon, Modal, message } from 'antd';
import _ from 'lodash';
import TitleItem from '../../components/TitleItem';
import UploadModal from '../../components/UploadModal';
import RenameModal from '../../components/UploadModal/RenameModal';
import PickerModal from '../../components/UploadModal/PickerModal';
import ViewImgModal from '../../components/UploadModal/ViewImgModal';
import config from '../../config';
import taskServer from '../../services/task';
import projectServer from '../../services/project';
import isSuccess from '../../utils/error';
import FileList from '../../components/FileList';

const { saveFile: saveProjectFile } = projectServer;
const { refleshFile, renameTaskFile, deleteTaskFiles, saveFile: saveTaskFile, viewFile } = taskServer;
const { baseUrl } = config;

const confirm = Modal.confirm;


class TaskMaterial extends Component {

    state = {
        showModal: false,
        files: []
    }

    componentWillMount() {
        const { create } = this.props;
        if (create) return;
        this.setBaseValue(this.props.detailData);
    }

    componentWillReceiveProps(nextProps) {
        const { create } = this.props;
        if (create) return;
        this.setBaseValue(nextProps.detailData);
    }

    setBaseValue = ({ files = [] }) => {
        this.setState({ files });
    }

    getValue = () => {
        const { files } = this.state;
        const list = files.map(v => ({
            recid: '', uploadfileid: v.fileid, filename: v.oldfilename
        }))
        return list
    }

    openModal = () => {
        const { create } = this.props;
        if (create) {
            message.warn('请创建任务后再上传资料文件');
            return;
        };
        this.setState({ showModal: true })
    }

    onChange = (e, i) => {
        const { files } = this.state;
        const newList = files.concat();
        newList[i] = { ...files[i], check: e.target.checked }
        this.setState({ files: newList });
    }

    onCheckedAll = (checkedAll) => {
        const { files } = this.state;
        const newList = files.map(f => ({ ...f, check: !checkedAll }));
        this.setState({ files: newList });
    }

    refleshFile = async (detailData, callback) => {
        const refleshData = await refleshFile({
            taskid: detailData.info.recid,
        })
        if (isSuccess(refleshData)) {
            this.setState({ files: refleshData.data });
            callback && callback();
        }
    }

    onRename = () => {
        const { files } = this.state;
        const checkList = files.filter(v => v.check);
        this.setState({ showRename: true, target: checkList[0] });
    }

    onRenameSure = async (newData, callback) => {
        const { detailData } = this.props;
        const res = await renameTaskFile(newData)
        // 成功更新数据
        if (isSuccess(res)) {
            this.refleshFile(detailData, callback);
        }
    }

    onCopy = () => {
        const { files } = this.state;
        const checkList = files.filter(v => v.check);
        this.setState({ pickerShow: true, target: checkList });
    }

    onCopySure = async (v, callback) => {
        const { target } = this.state;
        const { detailData } = this.props;
        let res;
        if (v.type === '1') {
            const files = target.map(t => ({
                folderid: v.folder.folderid, // 不知道有什么用的，但还是要传
                items: [{
                    folderid: v.folder.folderid, uploadfileid: t.uploadfileid,
                    filename: t.filename, sourcefilename: t.sourcefilename,
                    extension: t.extension,
                }]
            }));
            res = await saveProjectFile({
                projectid: v.project.recid,
                stageid: v.stage.stageid,
                files
            })
        } else if (v.type === '2') {
            const files = target.map(t => ({ filename: t.filename, recid: t.recid, sourcefilename: t.sourcefilename, uploadfileid: t.uploadfileid }));
            res = await saveTaskFile({
                taskid: v.task.recid,
                files
            })
        }

        // 成功更新数据
        if (isSuccess(res)) {
            message.success('转发文件成功');
            this.refleshFile(detailData, callback);
        }
    }

    onDelete = () => {
        const { files } = this.state;
        const { detailData, create } = this.props;
        if (create) {
            const newList = files.filter(v => !v.check);
            this.setState({ files: newList });
            return;
        }
        const checkList = files.reduce((pre, v) => v.check ? pre.concat(v.recid) : pre, []);
        confirm({
            title: '确认删除已选的文件？',
            content: '',
            okText: "确定",
            cancelText: "取消",
            onOk: async () => {
                const queen = checkList.map(c => {
                    return deleteTaskFiles({
                        taskid: detailData.info.recid,
                        filerecid: c
                    });
                });

                const allRes = await Promise.all(queen);
                console.log('allResallResallResallRes', allRes);
                // 成功更新数据
                this.refleshFile(detailData, () => {
                    message.success('删除成功！');
                });
            },
        });
    }

    onDownload = () => {
        const { files } = this.state;
        const checkList = files.reduce((pre, f) => {
            if (f.check) {
                return pre.concat({
                    ...f, url: `${baseUrl}/file/${f.newfilename}`
                })
            } else return pre;
        }, []);
        // 由于使用a标签的默认download属性会有文件名无法自定义问题，要使用node+electron来下载
        const { ipcRenderer } = window.electron;
        ipcRenderer.send('download', { files: checkList });
    }

    onUploadResult = (allRes, callback) => {
        const { detailData } = this.props;
        // 成功更新数据
        this.refleshFile(detailData, callback);
    }

    onViewFile = async (file, icon) => {
        if (window.isOpenPreviewItem) {
            message.warn('正在打开文件，请稍后...');
            return;
        }
        if (!file.isviewed) {
            const res = await viewFile({ fileid: file.fileid });
            // 成功更新数据
            if (isSuccess(res)) {
                const { detailData } = this.props;
                this.refleshFile(detailData);
            }
        }
        // 避免多次订阅，订阅打开应用的回调放在/src/pages/dashboard/index.js文件里面，添加isOpenPreviewItem标记正在打开
        window.isOpenPreviewItem = true;
        const { ipcRenderer } = window.electron;
        ipcRenderer.send("preview", { ...file, url: `${baseUrl}/file/${file.newfilename}` });
        // if(icon !== 'picture') {
        //     message.warn('暂时只能预览图片！');
        //     return;
        // };
        // this.setState({ imgUrl: `${baseUrl}/file/${file.newfilename}` });
    }

    // 未读在前面，已读在后面，并且按时间排序
    sortFiles = (files) => {
        if (files && files.length) {
            let newFiles = files;
            const hasRead = [];
            const unRead = [];
            files.forEach(f => {
                if (f.isviewed) hasRead.push(f);
                else unRead.push(f);
            });
            newFiles = [...unRead, ...hasRead];
            return newFiles;
        }
        return files;
    }

    render() {
        const { create, detailData, col, isShowInSlider } = this.props;
        const { showModal, files, showRename, pickerShow, target, imgUrl } = this.state;
        const checkList = files.filter(v => v.check);
        this.isBoss = _.get(detailData, 'info.ismanager') || _.get(detailData, 'info.ishost');
        const isFinish = _.get(detailData, 'info.taskstatus') === 2;
        // 任务详情绑定了项目阶段则隐藏上传按钮
        const projectid = _.get(detailData, 'info.projectid');
        const hiddenPlus = (!create && projectid) || isFinish;
        const checkedAll = checkList.length === files.length;
        return (
            <>
                <TitleItem
                    title="任务资料"
                    onClick={this.openModal}
                    icon={!hiddenPlus ? <Icon type="plus" className="mainColor" /> : null}
                    lineBreakShowOptionsNum={isShowInSlider ? 4 : undefined}
                    options={[
                        { key: 'onCheckedAll', name: checkedAll ? '取消全选' : '全选', onClick: () => this.onCheckedAll(checkedAll), show: files.length > 1 },
                        { key: 'onRename', name: '重命名', onClick: this.onRename, show: checkList.length === 1 && this.isBoss && !isFinish },
                        { key: 'onDownload', name: '下载', onClick: this.onDownload, show: checkList.length },
                        { key: 'onCopy', name: '转发', onClick: this.onCopy, show: checkList.length },
                        { key: 'onDelete', name: '删除', onClick: this.onDelete, show: checkList.length && this.isBoss && !isFinish },
                    ]}
                />
                <FileList
                    col={col}
                    isShowInSlider={isShowInSlider}
                    files={this.sortFiles(files)}
                    mainKey={'recid'}
                    checkedKey={'check'}
                    onChange={this.onChange}
                    onClick={this.onViewFile}
                />
                {create ? null : (
                    <ViewImgModal
                        show={imgUrl}
                        onCancel={() => this.setState({ imgUrl: undefined })}
                    />
                )}
                {create ? null : (
                    <RenameModal
                        data={target}
                        onChange={this.onRenameSure}
                        show={showRename}
                        onCancel={() => this.setState({ showRename: false })}
                    />
                )}
                {create ? null : (
                    <PickerModal
                        title="请选择目标文件夹/任务"
                        type={'1'}
                        visible={pickerShow}
                        onOk={this.onCopySure}
                        onCancel={() => this.setState({ pickerShow: false })}
                    />
                )}
                {create ? null : (
                    <UploadModal
                        type={'2'}
                        taskid={detailData.info.recid}
                        show={showModal}
                        onUploadResult={this.onUploadResult}
                        onCancel={() => this.setState({ showModal: false })}
                    />
                )}
            </>
        );
    }
}

export default TaskMaterial